<!--
 * @Author: jdy
 * @Date: 2024-05-13 09:09:06
 * @LastEditTime: 2024-06-05 09:33:21
 * @LastEditors: JZ\17778 17778169975@163.com
 * @FilePath: \zhlx-autoform-ui\src\components\ZHLX-Components\ZHLX-documentNumber\index.vue
 * @Description: 文号选择
-->
<template>
  <el-dialog v-model="visible" :title="title" draggable destroy-on-close :close-on-click-modal="false" append-to-body
    @closed="handleCloseDialog">
    <div class="form-dialog-body">
      <el-radio-group v-model="documentform.type" @change="handleTabChange">
        <el-radio :value="'DEFAULT'">系统生成</el-radio>
        <el-radio :value="'BROKEN'">选择断号</el-radio>
        <el-radio :value="'RESERVED'">选预留文号</el-radio>
        <el-radio :value="'CUSTOM'">自定义</el-radio>
      </el-radio-group>
      <el-divider />
      <el-form ref="documentformRef" :model="documentform" :rules="rules">
        <el-row>
          <el-col :span="8">
            <el-form-item label="机构代字:" prop="agencyName" v-if="documentform.type != 'CUSTOM'"
              style="margin-right: 5px;">
              <el-select filterable v-model="documentform.agencyName" placeholder="请选择机构代字"
                @change="handleAgencyNameChange" value-key="id" :loading="loadingagencyName">
                <el-option v-for="(item, index) in agencyNameList" :key="index" :label="item.agencyName"
                  :value="item.agencyName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年份:" prop="year" v-if="documentform.type != 'CUSTOM'" style="margin-right: 5px;">
              <el-select filterable v-model="documentform.year" placeholder="请选择年份" @change="yearChange" value-key="id">
                <el-option v-for="(item, index) in yearsList" :key="index" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="流水号:" prop="number" v-if="documentform.type == 'DEFAULT'">
              <el-input v-model="documentform.number" type="number" :min="documentform.serialNumberyuan"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="margin-top: 20px;" v-loading="numberLoading">
            <!-- 断号 -->
            <el-col :span="20">
              <el-form-item label=" " prop="brokenNumber" v-if="documentform.type == 'BROKEN'">
                <el-select-v2
                  v-model="documentform.brokenNumber"
                  :options="brokenList"
                  :props="{label: 'number', value: 'number',}"
                  placeholder="请选择断号"
                  filterable
                />
              </el-form-item>
            </el-col>
            <!-- 预留文号 -->
            <el-col :span="20">
              <el-form-item label=" " prop="reservedNumber" v-if="documentform.type == 'RESERVED'">
                <el-select-v2
                  v-model="documentform.reservedNumber"
                  :options="reservedList"
                  :props="{label: 'number', value: 'number',}"
                  placeholder="请选择预留文号"
                  filterable
                />
              </el-form-item>
            </el-col>
            <!-- 自定义文号 -->
            <el-col :span="20">
              <el-form-item label=" " prop="title" v-if="documentform.type == 'CUSTOM'">
                <el-input v-model="documentform.title" placeholder="请输入自定义文号"></el-input>
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="confirm('documentformRef')" :loading="btnLoading">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { generateId } from "@/utils/util";
import { getDocNumRecordListAPI, getBrokenListAPI, getDocNumAPI, getAgencyName, getYearByAgencyName, userUpdateDocNum, checkDocNum, getDocNumListdata } from "@/api/document/number";

export default {
  name: "document-number",
  componentName: 'FieldWidget',  //必须固定为FieldWidget，用于接收父级组件的broadcast事件
  props: {
    dataForm: {
      type: Object,
      default: () => { },
    },
    title: {
      type: String,
      default: "",
    },
    // 是否可跨前后一年
    isSelectYear: {
      type: Boolean,
      default: false,
    },

  },
  data () {
    return {
      oldFieldValue: null, //field组件change之前的值
      fieldModel: null,
      rules: {
        number: [
          { required: true, message: '请输入流水号', trigger: 'blur' },
        ],
        brokenNumber: [
          { required: true, message: '请选择断号', trigger: 'change' },
        ],
        reservedNumber: [
          { required: true, message: '请选择预留文号', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入自定义文号', trigger: 'blur' }
        ],
        year: [
          { required: true, message: '请选择年份', trigger: 'change' }
        ],
        agencyName: [
          { required: true, message: '请选择机构代字', trigger: 'change' }
        ],
      },
      widgetKey: '',
      visible: false,
      agencyNameList: [], //机构代字列表
      brokenList: [], //断号列表
      reservedList: [], //预留文号列表
      yearsList: [],   //年份
      documentform: {
        type: 'DEFAULT', //文号类别(RESERVED:预留文号, OFFLINE:线下占用,BROKEN:断号,CUSTOM:自定义文号,DEFAULT:系统生成)
        agencyName: '', //机构代字
        year: '', //年份
        documentNumber: '', //公文号
        number: '', //流水号
        brokenNumber: '', //断号
        reservedNumber: '', //预留文号
        title: '', //自定义文号
        numberSuffix: "",//单位
        yearPrefix: '',  //年份前缀
        yearSuffix: '',//年份后缀
        serialNumberyuan: '',
        several: 0
      },
      APIData: {
        'BROKEN': getBrokenListAPI,
        'RESERVED': getDocNumRecordListAPI,
      },
      nowDate: '',
      minTime: '',
      maxTime: '',
      btnLoading: false,
      loadingagencyName: false,
      numberLoading: false,
    }
  },
  computed: {

  },
  beforeCreate () {
    /* 这里不能访问方法和属性！！ */
  },

  created () {
    this.nowDate = new Date().getFullYear()
    this.minTime = this.isSelectYear ? this.nowDate - 1 : this.nowDate
    this.maxTime = this.isSelectYear ? this.nowDate + 1 : this.nowDate
  },

  mounted () {

  },

  beforeUnmount () {
  },

  methods: {

    refreshWidgetKey () {  //强制刷新组件！！
      this.widgetKey = 'select-key-' + generateId()
    },
    /**
     * 初始化
     */
    async init (businessRelationProp) {
      console.log("文种", businessRelationProp)
      this.visible = true;
      if (!businessRelationProp.documentTypeId) {
        this.$message.warning("无法获取到机构代字，请先绑定文种")
      } else {
        this.loadingagencyName = true;
        this.getDocNumList(businessRelationProp.documentTypeId)
      }
    },
    /**
     * 获取机构代字列表
     */
    async getDocNumList (documentTypeId) {
      await getDocNumListdata(documentTypeId).then(res => {
        this.loadingagencyName = false;
        this.agencyNameList = res.data;
      })
    },
    /**
     * 根据机构代字获取年份
     */

    async getYears (name) {
      await getYearByAgencyName(name).then(res => {
        try {
          this.yearsList = res.data;
        } catch (err) {
          this.$message.error(res.msg || '获取失败')
        }

      })
    },
    /**
     * 年份事件
     */
    yearChange () {
      this.getList();
    },
    /**
     * 选择机构代字和年份后回调
     */
    async getList () {
      if (!(this.documentform.agencyName && this.documentform.year)) { return }
      // getDocNumAPI
      this.numberLoading = true;
      await getDocNumAPI(this.documentform).then(res => {
        try {
          this.documentform.numberSuffix = res.data.numberSuffix;
          this.documentform.yearPrefix = res.data.yearPrefix;
          this.documentform.yearSuffix = res.data.yearSuffix;
          this.documentform.several = res.data.several;

          if (this.documentform.type == 'DEFAULT') {
            this.documentform.number = res.data.num;
            this.documentform.serialNumberyuan = res.data.num;
          } else if (this.documentform.type == 'BROKEN') {
            this.brokenList = res.data.list;
          } else if (this.documentform.type == 'RESERVED') {
            this.reservedList = res.data.list;
          }
        } catch (err) {
          this.$message.error(res.msg || '获取失败')
        }
      }).finally(() => {
        this.numberLoading = false;
      })
    },
    /**
     * 机构代字改变
     * @param {*} val 
     */
    handleAgencyNameChange (val) {
      console.log("机构代字改变", val);
      this.documentform.year = '';
      this.getYears(val);
    },
    /**
     * 关闭弹窗
     */
    handleCloseDialog () {
      this.resetForm()
      this.documentform.type = 'DEFAULT'
      this.btnLoading = false;
    },
    /**
     * 切换tab
     * @param {*} tab 
     * @param {*} event 
     */
    handleTabChange () {
      this.resetForm()
      this.documentform.title = '';
    },
    /**
     * 重置表单
     */
    resetForm () {
      this.yearsList = [];
      this.documentform.year = '';
      for (const i in this.documentform) {
        if (i == 'type' || i == 'year') { continue }
        this.documentform[i] = ''
      }
    },
    // 自定义调用保存
    async customChange () {
      await getDocNumAPI(this.documentform)
    },

    // 系统自动生成后用户修改文号调用  
    async userUpdateDocNumChange (num) {
      await userUpdateDocNum(this.documentform).then(res => {
        this.$emit('confirm', num, this.documentform);
        this.visible = false;
      }).catch(res => {
        //       // 判断是否被 预留/断号 占用 
        if (res.data == 'RESERVED') {
          this.$confirm(res.msg, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$emit('confirm', num, this.documentform);
            this.visible = false
          }).catch(() => {
            this.documentform.agencyName = '';
            this.documentform.year = '';
            this.documentform.number = ''
          });
        } else if (res.data == 'OFFLINE') {
          this.$alert(res.msg, '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.documentform.agencyName = '';
              this.documentform.year = '';
              this.documentform.number = ''
            }
          });
        } else {
          this.$message.error(res.msg || '获取失败1111111')
          this.btnLoading = false;
        }
      })
    },

    /**
     * 关闭弹窗
     */
    close () {
      this.visible = false;
      this.btnLoading = false;
    },
    /**
     * 打开弹窗
     */
    open () {
      this.visible = true;
    },

    /**
     * 保存文号
     */
    confirm (formName) {
      var that = this;
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.btnLoading = true
          let num;
          let paddedStr;
          //系统生成
          if (this.documentform.type == 'DEFAULT') {
            let strnumber = this.documentform.number + '';
            if (this.documentform.several != 1) {
              paddedStr = strnumber.padStart(this.documentform.several, "0"); // 补齐到字符串，用"0"填充
            } else {
              paddedStr = this.documentform.number;
            }
            num = this.documentform.agencyName + this.documentform.yearPrefix + this.documentform.year + this.documentform.yearSuffix + paddedStr + this.documentform.numberSuffix;

            this.btnLoading = false;
            if (this.documentform.serialNumberyuan != this.documentform.number) {
              this.userUpdateDocNumChange(num);
              // const resAlert = await userUpdateDocNum(this.documentform);

            } else {
              this.$emit('confirm', num, this.documentform);
              this.visible = false;
            }
            //预留文号
          } else if (this.documentform.type == 'BROKEN') {
            // num = this.documentform.brokenNumber
            let strnumber = this.documentform.brokenNumber + '';
            if (this.documentform.several != 1) {
              paddedStr = strnumber.padStart(this.documentform.several, "0"); // 补齐到字符串，用"0"填充
            } else {
              paddedStr = this.documentform.brokenNumber;
            }
            num = this.documentform.agencyName + this.documentform.yearPrefix + this.documentform.year + this.documentform.yearSuffix + paddedStr + this.documentform.numberSuffix;
            this.$emit('confirm', num, this.documentform);
            this.visible = false
            //断号
          } else if (this.documentform.type == 'RESERVED') {
            // num = this.documentform.reservedNumber
            let strnumber = this.documentform.reservedNumber + '';
            if (this.documentform.several != 1) {
              paddedStr = strnumber.padStart(this.documentform.several, "0"); // 补齐到字符串，用"0"填充
            } else {
              paddedStr = this.documentform.reservedNumber;
            }
            num = this.documentform.agencyName + this.documentform.yearPrefix + this.documentform.year + this.documentform.yearSuffix + paddedStr + this.documentform.numberSuffix;
            this.$emit('confirm', num, this.documentform);
            this.visible = false
            //自定义
          } else if (this.documentform.type == 'CUSTOM') {
            num = this.documentform.title;
            this.customChange();
            this.$emit('confirm', num, this.documentform);
            this.visible = false
          }
        }
      })
    },
    /**
     * 日期选择器 设置可选范围
     * 默认只能选当前年 | isSelectYear 可跨前后一年
     * @param {*} time date-picker的每一项
     */
    disabledDate (time) {
      return time.getFullYear() < this.minTime || time.getFullYear() > this.maxTime
    }
  }
}
</script>

<style lang="scss" scoped>
.full-width-input {
  width: 100% !important;
}

.form-dialog-body {
  padding: 20px;
}
</style>
